<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Sign extends Backend
{

    /**
     * Sign模型对象
     * @var \app\admin\model\Sign
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Sign;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if(empty($params['month'])){
                    $this->error("缺少月份");
                }

                $month_time = strtotime($params['month']);
                if($month_time < 10000){
                    $this->error("月份格式不正确");
                }
                $check_month = Db::table('sign')->where(['month'=>$params['month']])->count();
                if($check_month){
                    $this->error("该月份已存在");
                }
                $date_list = \app\admin\model\Sign::getMonthDate($params['month']);
                $date_sign_json = [];
                foreach ($date_list as $date){
                    if(!isset($params[$date])){
                        $this->error("缺少月份天数");
                    }
                    $date =  $params[$date]['date']??"";
                    $reward = $params[$date]['reward']??"";
                    $num = $params[$date]['num']??0;
                    $num = $num<=0?0:$num;
                    if(empty($date)){
                        $this->error("缺少月份天数");
                    }
                    if(empty($reward)){
                        $num = 0;
                    }
                    if($num==0){
                        $reward = "";
                    }
                    $date_sign_json[$date]=[
                        'date'=>$date,'reward'=>$reward,'num'=>$num
                    ];
                }

                $add_up_sign_arr = [];
                if($params['date_num'] && is_array($params['date_num'])){
                    foreach ($params['date_num'] as $k=>$date_num){
                        $date_num = (int)$date_num;
                        $reward = $params['reward'][$k]??"";
                        $num = (int)($params['num'][$k]??0);
                        if($date_num<1 || empty($reward) || $num<1){
                            continue;
                        }
                        $add_up_sign_arr[$date_num] = [
                            'date_num'=>$date_num,
                            'reward'=>$reward,
                            'num'=>$num
                        ];
                    }
                }
                $date_sign_json = $date_sign_json?json_encode($date_sign_json,JSON_UNESCAPED_UNICODE):"";
                $add_up_sign_json = $add_up_sign_arr?json_encode($add_up_sign_arr,JSON_UNESCAPED_UNICODE):"";
                $add_data = [
                    'month'=>$params['month'],
                    'date_sign'=>$date_sign_json,
                    'add_up_sign'=>$add_up_sign_json,
                    'status'=>$params['status']
                ];
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($add_data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $month = date("Y-m");
        $m_start_date = date("Y-m-d",strtotime($month));
        $m_end_date = date("Y-m-d",strtotime(date("Y-m",strtotime("+1 month",strtotime($month))))-1);
        $start_time = strtotime($m_start_date);
        $end_time = strtotime($m_end_date);
        $date_list = [];
        for ($i= $start_time;$i<=$end_time;$i+=86400){
            $date_list[]= date("Y-m-d",$i);
        }
//        p($date_list);die;
        $prop_list = Db::table('prop')->field(['id','name','coin','code'])->select();
        $skin_list = Db::table('skin')->where("type","<>","farm")->field(['id','name','coin','code'])->select();

        $data_list = [];
        foreach ($prop_list as $val){
            $data_list['prop='.$val['code']]=$val['name']." --- 金币价格:".$val['coin'];
        }
        foreach ($skin_list as $val){
            $data_list['skin='.$val['code']]=$val['name']." --- 金币价格:".$val['coin'];
        }
        $data_list['coin'] = "金币";

        $this->assign("date_list",$date_list);
        $this->assign("data_list",$data_list);
        return $this->view->fetch();
    }

    public function getDate(){
        $month = $this->request->post("month");
        if(empty($month)){
            $month = date("Y-m");
        }
        $m_start_date = date("Y-m-d",strtotime($month));
        $m_end_date = date("Y-m-d",strtotime(date("Y-m",strtotime("+1 month",strtotime($month))))-1);
        $start_time = strtotime($m_start_date);
        $end_time = strtotime($m_end_date);
        $date_list = [];
        for ($i= $start_time;$i<=$end_time;$i+=86400){
            $date_list[]= date("Y-m-d",$i);
        }
        $prop_list = Db::table('prop')->field(['id','name','coin','code'])->select();
        $skin_list = Db::table('skin')->where("type","<>","farm")->field(['id','name','coin','code'])->select();
        $data_list = [];
        foreach ($prop_list as $val){
            $data_list['prop='.$val['code']]=$val['name']." --- 金币价格:".$val['coin'];
        }
        foreach ($skin_list as $val){
            $data_list['skin='.$val['code']]=$val['name']." --- 金币价格:".$val['coin'];
        }
        $data_list['coin'] = "金币";

        $str = "";
        foreach ($date_list as $k=>$val){

        $str.= '<div class="input-group">
                <span class="input-group-addon">日期： </span>
                <input type="text" readonly="readonly" name="row['.$val.'][date]" value="'.$val.'" class="form-control">
                <span class="input-group-addon"> 奖励：</span>
                <select class="form-control" name="row['.$val.'][reward]">';
                    foreach($data_list as $k1=>$val1){
                        $str.='<option value="'.$k1.'">'.$val1.'</option>';
                    }
              $str.=' </select>
                <span class="input-group-addon">数量：</span>
                <input   name="row['.$val.'][num]" type="number" min="1" value="1" class="form-control">
            </div>
            <p />
        </div>';
        }

        $this->assign("date_list",$date_list);
        $this->assign("data_list",$data_list);
       // return $this->view->fetch();
        return view('get_date',['name'=>'thinkphp']);


        // $this->success('请求成功',['html'=>$str]);
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if(empty($params['month'])){
                    $this->error("缺少月份");
                }
                $month_time = strtotime($params['month']);
                if($month_time < 10000){
                    $this->error("月份格式不正确");
                }
                $check_month = Db::table('sign')->where(['month'=>$params['month']])->where("id","<>",$ids)->count();
                if($check_month){
                    $this->error("该月份已存在");
                }
                $date_list = \app\admin\model\Sign::getMonthDate($params['month']);
                $date_sign_json = [];
                foreach ($date_list as $date){
                    if(!isset($params[$date])){
                        $this->error("缺少月份天数");
                    }
                    $date =  $params[$date]['date']??"";
                    $reward = $params[$date]['reward']??"";
                    $num = $params[$date]['num']??0;
                    $num = $num<=0?0:$num;
                    if(empty($date)){
                        $this->error("缺少月份天数");
                    }
                    if(empty($reward)){
                        $num = 0;
                    }
                    if($num==0){
                        $reward = "";
                    }
                    $date_sign_json[$date]=[
                        'date'=>$date,'reward'=>$reward,'num'=>$num
                    ];
                }

                $add_up_sign_arr = [];
                if($params['date_num'] && is_array($params['date_num'])){
                    foreach ($params['date_num'] as $k=>$date_num){
                        $date_num = (int)$date_num;
                        $reward = $params['reward'][$k]??"";
                        $num = (int)($params['num'][$k]??0);
                        if($date_num<1 || empty($reward) || $num<1){
                            continue;
                        }
                        $add_up_sign_arr[$date_num] = [
                            'date_num'=>$date_num,
                            'reward'=>$reward,
                            'num'=>$num
                        ];
                    }
                }
                $date_sign_json = $date_sign_json?json_encode($date_sign_json,JSON_UNESCAPED_UNICODE):"";
                $add_up_sign_json = $add_up_sign_arr?json_encode($add_up_sign_arr,JSON_UNESCAPED_UNICODE):"";
                $update_data = [
                    'month'=>$params['month'],
                    'date_sign'=>$date_sign_json,
                    'add_up_sign'=>$add_up_sign_json,
                    'status'=>$params['status']
                ];


                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($update_data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $date_sign = $row->date_sign;
        $add_up_sign = $row->add_up_sign;
        $date_sign = $date_sign?json_decode($date_sign,true):[];
        $add_up_sign = $add_up_sign?json_decode($add_up_sign,true):[];


        $prop_list = Db::table('prop')->field(['id','name','coin','code'])->select();
        $skin_list = Db::table('skin')->field(['id','name','coin','code'])->select();
        $data_list = [];
        foreach ($prop_list as $val){
            $data_list['prop='.$val['code']]=$val['name']." --- 金币价格:".$val['coin'];
        }
        foreach ($skin_list as $val){
            $data_list['skin='.$val['code']]=$val['name']." --- 金币价格:".$val['coin'];
        }
        $data_list['coin'] = "金币";
        $month = $row->month;
        if(empty($month)){
            $month = date("Y-m");
        }
        $date_list = \app\admin\model\Sign::getMonthDate($month);


        $this->view->assign("row", $row);
        $this->view->assign("date_list", $date_list);
        $this->view->assign("date_sign", $date_sign);
        $this->view->assign("data_list", $data_list);
        $this->view->assign("add_up_sign", $add_up_sign);
        return $this->view->fetch();
    }


}
